<template>
  <div class="app-container">
    <h2 style="text-align: center">发布新课程</h2>

    <el-steps
      active="1"
      process-status="wait"
      align-center
      style="margin-bottom: 40px"
    >
      <el-step title="填写课程基本信息" />
      <el-step title="创建课程大纲" />
      <el-step title="最终发布" />
    </el-steps>
    <div class="info">
      <el-form :model="couresinfo" label-width="auto" style="max-width: 600px">
        <el-form-item label="课程标题">
          <el-input v-model="couresinfo.title" />
        </el-form-item>
        <el-form-item label="课程分类">
          <el-select
            v-model="couresinfo.subjectParentId"
            placeholder="Select"
            style="width: 200px"
            @change="subjectLevelOneChanged"
          >
            <el-option
              v-for="item in SubjectOneList"
              :key="item.id"
              :label="item.title"
              :value="item.id"
            />
          </el-select>
          <!-- 二级分类 -->
          <el-select
            v-model="couresinfo.subjectId"
            placeholder="请选择二级分类"
            style="max-width: 200px"
          >
            <el-option
              v-for="subject in SubjectTwoList"
              :key="subject.id"
              :label="subject.title"
              :value="subject.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="讲师类别">
          <el-select v-model="couresinfo.teacherId" placeholder="请选择">
            <el-option
              v-for="teacher in teacherList"
              :key="teacher.id"
              :label="teacher.name"
              :value="teacher.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="课时" prop="lesson">
          <el-input-number
            v-model="couresinfo.lessonNum"
            :min="0"
            controls-position="right"
          />
        </el-form-item>
        <el-form-item label="课程状态">
          <el-select
            v-model="couresinfo.status"
            clearable
            placeholder="课程状态"
            style="width: 200px"
          >
            <el-option value="Draft" label="未发布" />
            <el-option value=" Normal" label="已发布" />
          </el-select>
        </el-form-item>
        <el-form-item label="课程简介" prop="description">
          <el-input
            v-model="couresinfo.description"
            :rows="5"
            type="textarea"
            placeholder="请输入课程简介"
          />
        </el-form-item>
        <el-form-item label="课程封面" prop="cover">
          <el-upload
            class="avatar-uploader"
            :action="uploadUrl + '/oss/upload-img'"
            :data="{ cateDir: 'course' }"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
          >
            <img v-if="imageUrl" :src="imageUrl" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="课程价格" prop="price">
          <el-input-number
            v-model="couresinfo.price"
            controls-position="right"
          />
        </el-form-item>
      </el-form>
    </div>

    <el-form label-width="120px">
      <el-form-item>
        <el-button type="primary" @click="next">保存并下一步</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import { ElMessage, UploadProps } from "element-plus";
import { reactive, ref } from "vue";
import { useRouter, useRoute } from "vue-router";
const uploadUrl = import.meta.env.VITE_URL;
import axios from "../../assets/js/axios";
const imageUrl = ref("");
const couresinfo = reactive({
  id: 0,
  title: "",
  subjectId: 0, //二级分类
  subjectParentId: 0, //一级分类
  teacherId: "",
  status: "",
  lessonNum: 0,
  description: "",
  price: 0,
});

const teacherList = ref<any>([]);
const SubjectOneList = ref<any>([]);

const SubjectTwoList = ref<any>([]);
const route = useRoute();
const courseId = ref(route.params.id || "");
const courseIdStr = String(courseId.value);
if (route.query.id) {
  //修改元信息标题
  console.log("id:", route.query.id);
  route.meta.title = "课程管理 / 课程编辑";
  // 发送请求显示编辑的信息
  axios
    .get("/serviceedu/edu-course/getCourseInfo/" + route.query.id, {})
    .then((res: any) => {
      console.log("res" + res);
      couresinfo.id = res.data.data.id;
      couresinfo.title = res.data.data.title;
      couresinfo.subjectParentId = res.data.data.subjectParentId;
      couresinfo.teacherId = res.data.data.teacherId;
      couresinfo.lessonNum = res.data.data.lessonNum;
      couresinfo.description = res.data.data.description;
      imageUrl.value = res.data.data.cover;
      couresinfo.price = res.data.data.price;
    });
}
const router = useRouter();
const next = () => {
  if (route.query.id) {
    axios
      .put("/serviceedu/edu-course/updateCourse", couresinfo)
      .then((res: any) => {
        if (res.code === 200) {
          ElMessage({
            type: "success",
            message: "修改课程成功",
          });
          // 跳转列表页
          router.push("/chapter/" + route.query.id);
        }
      });
  } else {
    axios
      .post("/serviceedu/edu-course/addCourseInfo", couresinfo)
      .then((res: any) => {
        if (res.code === 200) {
          ElMessage({
            type: "success",
            message: "添加课程成功",
          });
          // 跳转列表页
          router.push("/courseList/");
        } else {
          console.log("error submit!");
        }
      });
  }
};

const handleAvatarSuccess: UploadProps["onSuccess"] = (response) => {
  console.log("response:", response);
  imageUrl.value = response.data.url;
  couresinfo.cover = response.data.url;
};
const subjectLevelOneChanged = (value: any) => {
  console.log(value);
  // 遍历 SubjectOneList 以找到匹配的项
  for (let i = 0; i < SubjectOneList.value.length; i++) {
    if (SubjectOneList.value[i].id === value) {
      // 更新 SubjectTwoList 为找到的项的 children
      SubjectTwoList.value = SubjectOneList.value[i].children;

      // 更新 couresinfo 的 subjectId（注意这里没有逗号）
      couresinfo.subjectId = 0; // 假设您想将 subjectId 设置为 0

      // 如果只想设置一个匹配项就退出循环（可选）
      break;
    }
  }
};

//查询讲师数据
const geTeacherList = () => {
  axios.get("/serviceedu/edu-teacher/TeacherList", {}).then((res: any) => {
    console.log(res);
    // 接收总条数
    teacherList.value = res.data.list;
  });
};
// 调用用户初始化查询数据方法
geTeacherList();

//查询所有的一级分类
const getSubjectOne = () => {
  axios.get("/serviceedu/edu-subject/getAllSubject", {}).then((res: any) => {
    console.log(res);
    SubjectOneList.value = res.data.list;
  });
};
// 调用用户初始化查询数据方法
getSubjectOne();
</script>

<style lang="less" scoped >
.info {
  margin-left: 150px;

  :deep .avatar-uploader {
    .avatar {
      width: 178px;
      height: 178px;
      display: block;
    }
    .el-upload {
      border: 1px dashed #cccccc;
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      transition: var(--el-transition-duration-fast);
    }
    .el-upload:hover {
      border-color: #409eff;
    }
  }
  .el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
  }
}
</style>